﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Hammock;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Marketplace;
using Microsoft.Xna.Framework.Media;
using MyMeetup.ViewModels;

namespace MyMeetup
{
    public partial class PhotoPage : PhoneApplicationPage
    {
        private List<Photo> _photos;
        private int _idx;
        private double initialAngle = 0;
        private double initialScale = 0;

        public PhotoPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(PageLoaded);
            //FrameworkElement root = Application.Current.RootVisual as FrameworkElement;
            //if(root != null)
            //    _photos = root.DataContext as List<Photo>;
            
        }
        

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (_photos == null && State.ContainsKey("CurrentPhotos"))
                _photos = State["CurrentPhotos"] as List<Photo>;

        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            State["CurrentPhotos"] = _photos;
        }


        private void PageLoaded(object sender, RoutedEventArgs e)
        {
            
            string url;
            if (!NavigationContext.QueryString.TryGetValue("url", out url)) return;

            var photos = ((PhotoPageViewModel) photoPivot.DataContext).CurrentPhotos;
            
            progressBar.IsIndeterminate = true;
            for (int i = 0; i < photos.Count; i++)
            {
                if (photos[i].photo_link == url)
                {
                    _idx = i;
                    break;
                }
            }

            photoPivot.SelectedIndex = _idx;
            progressBar.IsIndeterminate = false;
        }

        private void OnPinchStarted(object sender, PinchStartedGestureEventArgs e)
        {
            var image = sender as System.Windows.Controls.Image;
            if (image == null) return;
            var transform = image.RenderTransform as CompositeTransform;
            if (transform == null) return;
            //initialAngle =  transform.Rotation;
            initialScale = transform.ScaleX;
        }

        private void OnPinchDelta(object sender, PinchGestureEventArgs e)
        {
             //ImageScaling.ScaleX = e.DistanceRatio;
             //   ImageScaling.ScaleY = e.DistanceRatio;
            var image = sender as System.Windows.Controls.Image;
            if (image == null) return;
            var transform = image.RenderTransform as CompositeTransform;
            if (transform == null) return;

            //transform.Rotation = initialAngle + e.TotalAngleDelta;
            transform.ScaleX = initialScale * e.DistanceRatio;
            transform.ScaleY = initialScale * e.DistanceRatio;
        }

        private void OnDragDelta(object sender, DragDeltaGestureEventArgs e)
        {
            var image = sender as System.Windows.Controls.Image;
            if (image == null) return;
            var transform = image.RenderTransform as CompositeTransform;
            if (transform == null) return;

            transform.CenterX = (transform.CenterX - e.HorizontalChange);
            transform.CenterY = (transform.CenterY - e.VerticalChange);

            if (transform.CenterX < 0)
                transform.CenterX = 0;
            else if (transform.CenterX > (image.Height * transform.ScaleX))
                transform.CenterX = image.Height * transform.ScaleX;

            if (transform.CenterY < 0)
                transform.CenterY = 0;
            else if (transform.CenterY > (image.Height * transform.ScaleY))
                transform.CenterY = image.Height * transform.ScaleY;
        }

        

        private void PhoneApplicationPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
        {
            //if(e.Orientation == PageOrientation.Portrait || e.Orientation == PageOrientation.PortraitUp || e.Orientation == PageOrientation.PortraitDown)
            //{
            //    currentImage.Height = 730;
            //}
            //else if(e.Orientation == PageOrientation.Landscape || e.Orientation == PageOrientation.LandscapeLeft || e.Orientation == PageOrientation.LandscapeRight)
            //{
            //    currentImage.Height = 420;
            //}

        }


        private void SavePhoto(object sender, EventArgs e)
        {
            if (LicenseHelper.IsTrial())
            {
                // show trial page
                NavigationService.Navigate(new Uri("/BuyNow.xaml", UriKind.Relative));
            }
            else
            {


                // Create a filename for JPEG file in isolated storage.
                String tempJPEG = "TempJPEG";

                // Create virtual store and file stream. Check for duplicate tempJPEG files.
                var myStore = IsolatedStorageFile.GetUserStoreForApplication();
                if (myStore.FileExists(tempJPEG))
                {
                    myStore.DeleteFile(tempJPEG);
                }

                IsolatedStorageFileStream myFileStream = myStore.CreateFile(tempJPEG);


                // Create a stream out of the sample JPEG file.
                // For [Application Name] in the URI, use the project name that you entered in the previous steps. Also TestImage.jpg is an example,
                //you must enter your JPEG filename if it is different.
                //StreamResourceInfo sri = null;
                Uri uri = new Uri(((Photo) photoPivot.SelectedItem).photo_link, UriKind.Absolute);
                //sri = Application.GetResourceStream(uri);
                int idx = uri.AbsolutePath.LastIndexOf('/');
                string filename = uri.AbsolutePath.Substring(idx + 1);


                WebClient webClient = new WebClient();
                webClient.OpenReadCompleted += delegate(object sender2, OpenReadCompletedEventArgs e2)
                                                   {
                                                       try
                                                       {
                                                           // Create a new WriteableBitmap object and set it to the JPEG stream.
                                                           BitmapImage bitmap = new BitmapImage();
                                                           bitmap.SetSource(e2.Result);
                                                           WriteableBitmap wb = new WriteableBitmap(bitmap);

                                                           Extensions.SaveJpeg(wb, myFileStream, wb.PixelWidth,
                                                                               wb.PixelHeight, 0, 85);
                                                           myFileStream.Close();

                                                           // Create a new stream from isolated storage, and save the JPEG file to the media library on Windows Phone.
                                                           myFileStream = myStore.OpenFile(tempJPEG, FileMode.Open,
                                                                                           FileAccess.Read);

                                                           MediaLibrary library = new MediaLibrary();
                                                           Picture pic = library.SavePicture(filename, myFileStream);
                                                           myFileStream.Close();
                                                           Dispatcher.BeginInvoke(
                                                               () =>
                                                               MessageBox.Show("Image saved!", "Success",
                                                                               MessageBoxButton.OK));
                                                       }
                                                       catch (Exception ex)
                                                       {
                                                           Dispatcher.BeginInvoke(
                                                               () =>
                                                               MessageBox.Show("There was an error saving the image."));
                                                       }

                                                   };
                webClient.OpenReadAsync(uri);

            }

        }

    }
}